package cn.wolfcode.mq;

import cn.wolfcode.config.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(consumerGroup = "orderMQResultConsumer",
                    topic = MQConstant.ORDER_RESULT_TOPIC
                    )
public class WSSeckillOrderListener implements RocketMQListener<OrderMQResult> {

    //根据token找到对应webSocket客户端，发送数据
    @SneakyThrows
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        /*
            睡一秒，等websocket客户端连接到webSocket服务器
         */
        Thread.sleep(1000);
        //根据token找到对应webSocket客户端，
        String token = orderMQResult.getToken();
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        // 发送数据到指定客户端
        String orderResultJsonString = JSON.toJSONString(orderMQResult);
        webSocketServer.getSession().getBasicRemote().sendText(orderResultJsonString);
    }
}
